import { PageContainer } from '@ant-design/pro-layout';
import { Button, message,Popconfirm,Form,Modal,Table,TreeSelect,Cascader, Tree} from 'antd';
import { FormattedMessage } from 'umi';
import ProTable from '@ant-design/pro-table';
import ProForm, { DrawerForm,ModalForm,ProFormDatePicker,ProFormSelect,ProFormText, ProFormUploadDragger } from '@ant-design/pro-form';
import React, { useState, useRef } from 'react';
import type { ProColumns,ActionType } from '@ant-design/pro-table';
import { FileExcelOutlined, PlusOutlined } from '@ant-design/icons';
import {SaleTeam,TreeData} from '../../../model';
import { querySalesTeam,salesTeamTree,areaTwo,saveSalesTeam,deleteSalesTeam,updateSalesTeam,salesCustomerData,saveCustomerData,insertSalesTeamArea,findSalesAreaBySalesId,deletSalesAreaById,exportSalesTeam,teamList} from '../service';
import {treeFind,treeEnable} from '../../../utils/utils'
import request from '@/utils/request';
import CustomerChoose from '@/components/Common/CustomerChoose';
import {exportFile} from '@/utils/utils';
import { Space } from 'antd';
import ReactDOM from 'react-dom';

export default () => {

  const [showCreate, setShowCreate] = useState(false);
  const [editModel, setEditModel] = useState<any>(undefined);
  const [fullArea, setFullArea] = useState<string>();
  const [currentData, setCurrentData] = useState<any[]>([]);
  const [areaData, setAreaData] = useState<any[]>([{label:'华东区',value:'1'},{label:'南区',value:'2'}]);
  const [treeData2, setTreeData2] = useState<any[]>([{title:'华东区',key:'1',children:[{title:'江苏省',key:'1-江苏省'},{title:'上海市',key:'1-上海市'}]},{title:'南区',key:'2',children:[{title:'云南省',key:'2-云南省'},{title:'广东省',key:'2-广东省'}]}]);

  const [showImport,setShowImport] = useState<boolean>(false);
  const [errorVisible,setErrorVisible] = useState<boolean>(false);
  const [custModalVisible,setCustModalVisible] = useState<boolean>(false);
  const [areaVisible,setAreaVisible] = useState<boolean>(false);
  const [errInfo,setErrInfo] = useState<any[]>([]);
  const [currentArea,setCurrentArea] = useState<any[]>([]);
  const [teamData,setTeamData] =  useState<any[]>([]);

  async function  requestTeamTree(){
    var val =await salesTeamTree();
    setTreeData(val.data); 
  }

  async function  requestAreas(){
    var val =await areaTwo();
    setAreas(val.data); 
  }

  async function requestTeam() {
    var val = await teamList({pageSize:100});
    setTeamData(val.data.map((item:any)=>{
      return {label:item.name,value:item.id}
    }))

  }
  
  
  const errorColumn=[
    {
      title: '错误行',
      dataIndex: 'rownum',
    },
    {
      title: '错误信息',
      dataIndex: 'errerMsg',
    },
  ]

  React.useEffect(()=>{
    //请求树数据
    requestTeamTree();
    requestAreas();
    requestTeam();
    return function cleanup() {};
  },[]);

const [treeData, setTreeData] = useState<TreeData[]>();
const [areas, setAreas] = useState<TreeData[]>();
const actionRef = useRef<ActionType>();

const handleDelete=async(id:string)=>{
  var val =await deleteSalesTeam({"ids":id});
  if(val.errorCode==='200'){
    message.success('删除成功');
    actionRef.current?.reloadAndRest?.();
  }else{
    message.error('删除失败');
  }
}

const areaColumns:ProColumns[] = [
  {
    title:'省份',
    dataIndex: 'provincesLabel',
  },
  {
    title:'城市',
    dataIndex: 'cityLabel',
  },
  {
    title: "操作",
    valueType: 'option',
    render: (text, record:any,_, action) => [
      <Popconfirm title="确定删除该区域吗?"     key="delete" onConfirm={async() => {
        var val = await deletSalesAreaById({"id":record.id});
          if(val.errorCode==='200'){
            var newData=areaData.filter((item:any) => item.cid !== record.cid);
            setAreaData(newData);
          }else{
            message.error(val.errorMessage);
          }

      }}>
        <a>删除</a>
      </Popconfirm>
    ],
  },
]

const hisColumns:ProColumns[] = [
  {
    title:'医院名称',
    dataIndex: 'customerName',
   
    ellipsis:true
  },
  {
    title:'创建日期',
    width:200,
    ellipsis:true,
    dataIndex: 'insertDate',
  },
  {
    title: "操作",
    width:120,
    valueType: 'option',
    render: (text, record:any,_, action) => [
      <Popconfirm title="确定删除该医院吗?"     key="delete" onConfirm={() => {
          var newData=currentData.filter((item:any) => item.customerId !== record.customerId);
          setCurrentData(newData);
      }}>
        <a>删除</a>
      </Popconfirm>
    ],
  },
]

  //表头信息以及表值设置
  const columns: ProColumns<SaleTeam>[] = [
    {
      title:'姓名',
      dataIndex: 'name',
    },
    {
      title: '电话',
      dataIndex: 'phone',
    },
    {
      title: '所属团队',
      dataIndex: 'teamName',
      hideInSearch:true,
    },
    {
      title: '邮箱',
      hideInSearch:true,
      dataIndex: 'mail',
     },
    {
      title: '岗位',
      dataIndex: 'part',
      hideInSearch:true,
    },
    {
      title: '地区',
      dataIndex: 'fullAddress',
      hideInSearch:true,
    },
    {
      title: '小区经理',
      dataIndex: 'pName',
      hideInSearch:true,
    },
    {
      title: '大区经理',
      dataIndex: 'superior',
      hideInSearch:true,
    },
    {
      title: "操作",
      valueType: 'option',
      render: (text, record:any,_, action) => [
        <a
          key="editable"
          onClick={async() => {
            record.areas=[record.provinces,record.city]
            if(record.pId==='0'){
              record.pId="";
            }
            setFullArea(record.fullAddress);
            treeEnable(treeData,false);
            const data = treeFind(treeData,(node)=>{
              return node.value === record.id
            });
            treeEnable(data,true);
            setEditModel(record);
            setShowCreate(true);

            var params:any={};
            params.salesId=record.id;
            params.pageSize=2000;
            var val = await salesCustomerData({...params});
            if(val.errorCode==='200'){
              setCurrentData(val.data);
            }
            // val = await findSalesAreaBySalesId({...params});
            // if(val.errorCode==='200'){
            //   val.data.forEach((e:any)=>{
            //     e.cid = `${e.provinces}-${e.city}`
            //   })
            //   setAreaData(val.data);
            // }


            console.log(teamData,record)
          }}
        >
          编辑
        </a>,
        <a key='deleteSale' onClick={async()=>{
          var val = await salesCustomerData({salesId:record.id,page:0,pageSize:10})
          if(val.total===0){
            Modal.confirm({
              title: '删除销售',
              content: '确定删除该销售吗？',
              okText: '确认',
              cancelText: '取消',
              onOk:()=>{
                handleDelete(record.id)
              }
            });
          }else{
            var msg = `${record.name}已绑定了${val.total}家医院，删除会同步解除其与医院的绑定关系，是否确认删除？`
            Modal.confirm({
              title: '删除销售',
              content: msg,
              okText: '确认',
              cancelText: '取消',
              onOk:()=>{
                handleDelete(record.id)
              }
            });

          }
        }}>删除</a>
        // <Popconfirm title="确定删除该销售吗?"     key="delete" onConfirm={() => handleDelete(record.id)}>
        //   <a>删除</a>
        // </Popconfirm>
      ],
    },
  ];

  function onChange(value,label) {
    if(label.length>1){
      const fullData = `${label[0].label}/${label[1].label}`;
      setFullArea(fullData);
    }else     if(label.length>0){
      const fullData = `${label[0].label}`;
      setFullArea(fullData);
    }else{
      setFullArea(""); 
    }
  }

  function onAreaChange(value:any,label:any){
      setCurrentArea(label);
  }

 const chooseCustomer: ProColumns[] = [
    {
      title:'医院编码',
      dataIndex: 'bh',
    },
    {
      title:"医院名称",
      dataIndex: 'name',
    },
    {
      title:"省",
      dataIndex: 'provinces',
      hideInTable:true,
    },
    {
      title:"市",
      dataIndex: 'city',
      hideInTable:true,
    },
    {
      title: '地区',
      dataIndex: 'city',
      valueType:'select',
      hideInSearch:true,
      renderText: (_,record: any) =>
      `${record.provinces}/${record.city}`
    },
    {
      title: '级别/等级',
      dataIndex: 'level',
      hideInSearch:true,
      renderText: (_,record: any) =>
      `${record.level}/${record.grade}`
    },
  ];

  const custData = (params:any)=>{
    var data = request('/xwyl/hospital/hospitalData',{params});
    return data;
  }

  const onFileUpload=(info:any)=>{
    if (info.file.status !== 'uploading') {
    }
    if (info.file.status === 'done') {
      if(info.file.response.errorCode==='200'){
        message.success(`${info.file.name} 上传成功，后台正在处理...`);
        actionRef.current?.reloadAndRest?.();
        setShowImport(false);
      }else{
        message.error('上传失败: '+info.file.response.msg);
        setErrorVisible(true);
        setErrInfo(info.file.response.data);
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败！`);
    }
  }

  const handleCancel=()=>{
    setErrorVisible(false);
    setErrInfo([]);
  }


  return (
    <PageContainer>
    <ProTable<SaleTeam>
      actionRef={actionRef}
      headerTitle='销售列表'
      pagination={{
        pageSizeOptions:['20', '100', '500']
      }}
      request={(params, sorter, filter) => querySalesTeam({...params,filter})}
      columns={columns}
      rowKey="id"
      search={{
        span: 6,
      }}
      toolBarRender={() => [
        <Button
          type="primary"
          key="primary"
          onClick={() => {
            treeEnable(treeData,false);
            setShowCreate(true);
          }}
        >
          <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
        </Button>,
        // <Button
        //   type="primary"
        //   key="primary"
        //   onClick={async() => {
        //     setShowImport(true);
        //   }}
        // >
        // <FileExcelOutlined />导入
        // </Button>,
        <Button
         type="primary"
         key="primary"
         onClick={async() => {
            var val = await exportSalesTeam({"isAll":1});
            if(val.errorCode==='200'){
              exportFile(val.data,'销售.xlsx');
            }else{
              message.error('导出失败');
            }
         }}
       >
        <FileExcelOutlined />导出
       </Button>
      ]}
      toolbar={{settings:[]}}
      />

         <DrawerForm
          title={editModel?"销售编辑":"销售新增"}
          drawerProps={{
            destroyOnClose: true,
          }}
           onVisibleChange={(v)=>{
            if(!v){
              setFullArea("");
              setEditModel(undefined);
              setCurrentData([]);
            }
            setShowCreate(v);
           }}
           visible={showCreate}
           onFinish={async (values: any) => {
             if(!values.pId){
                values.pId="0"
             }
             if(values.areas&&values.areas.length>0){
                values.provinces = values.areas[0];
                if(values.areas.length>1){
                  values.city = values.areas[1];
                }
             }
             values.fullAddress = fullArea;
             var val ;
             if(editModel){
              values.id=editModel.id;
              val = await updateSalesTeam(values);
             }else{
              val = await saveSalesTeam(values);
             }
             if(val.errorCode==='200'){
                //保存下授权的医院信息
                if(editModel){
                  var hisData:any={'salesId':editModel?.id,'customer':currentData}
                  val =await saveCustomerData(hisData);
                  if(val.errorCode!='200'){
                    message.error(val.errorMessage);
                    return false;
                  }else{
                    message.success('提交成功');
                    actionRef.current?.reloadAndRest?.();
                    requestTeamTree();
                    return true;
                  }
                }
                message.success('提交成功');
                actionRef.current?.reloadAndRest?.();
                requestTeamTree();
                return true;
              }else{
                message.error(val.errorMessage);
                return false;
              }
           }}
           
         >
           <ProFormText  name="name" label="姓名" placeholder="请输入姓名"
                initialValue={editModel?.name}
                rules={[
                  {
                    required: true,
                  },
                ]}/>

           <ProFormSelect name="teamId" initialValue={editModel?.teamId} label="所属团队" rules={[
                  {
                    required: true,
                  },
                ]} options={teamData}/>

           <ProFormText  name="phone" label="电话" placeholder="请输入电话" 
                initialValue={editModel?.phone}
               />
           <ProFormText  name="mail" label="邮箱" placeholder="请输入邮箱"
                initialValue={editModel?.mail}
                rules={[
                  {
                    required: true,
                  },
                  {
                    pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
                    message: '邮箱格式不正确',
                  },
                  {
                    max: 50,
                    message: '邮箱不得超过50字符',
                  },
                ]} />
            <ProFormSelect name="pType" initialValue={editModel?.pType} label="管理等级" options={[{"label":"无","value":"0"},{"label":"小区经理","value":"1"},{"label":"大区经理","value":"2"}]}/>
            <ProFormText  name="part" label="岗位" placeholder="请输入岗位"   initialValue={editModel?.part}
            />

         <Form.Item
            name="pId"
            label="上级（不选择默认顶级）"
            initialValue={editModel?.pId}
          >
            <TreeSelect
              style={{ width: '100%' }}
              allowClear={true}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={treeData}
              placeholder="请选择"
              treeDefaultExpandAll
          />
         </Form.Item>
         {/* <Form.Item
            name="areas"
            label="省/市"
            initialValue={editModel?.areas}
          >
            <Cascader
              changeOnSelect
              options={areas}
              // value={editModel?.areas}
              placeholder="请选择"
              onChange={onChange}
          />
         </Form.Item> */}
        <Form.Item style={{
          width: 330
        }} name='area' label='所属大区/省份'>
           <Tree
              checkable
              defaultExpandAll
              treeData={treeData2}
            />
        </Form.Item>
         {editModel?
         
         [
         <ProTable
            key="his"
            headerTitle='医院列表'
            dataSource={currentData}
            columns={hisColumns}
            rowKey="id"
            tableAlertOptionRender={({selectedRowKeys,onCleanSelected}) => {
              return (
                <Space size={16}>
                  <a key="i2" style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                    取消选择
                  </a>
                  {/* <Form.Item style={{marginBottom:-20}}>
                     <ProFormDatePicker fieldProps={{onChange:(val:any)=>{
                      if(val){
                        console.log(val.format('YYYY-MM-DD'),"--------")
                      }
                    }}} name="hosDate"></ProFormDatePicker>
                </Form.Item>
                  <a key="i1" onClick={()=>{
                 
                  }}>设置生效日期</a> */}
                  <a key="i1" onClick={()=>{
                    var newData=currentData.filter((item:any) => selectedRowKeys.indexOf(item.id)<0)
                    setCurrentData(newData);
                  }}>删除</a>
                </Space>
              );
            }}
            rowSelection={{
              selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            }}
            search={false}
            toolBarRender={() => [
              <Button
                type="primary"
                key="addH"
                onClick={() => {
                  setCustModalVisible(true);
                }}
              >
                <PlusOutlined />添加
              </Button>
            ]}
            toolbar={{settings:[]}}
            pagination={{
              pageSizeOptions:['20', '100', '500']
            }}
         />]:<a key="o"></a>}
         
         </DrawerForm>

         <CustomerChoose
              onCancel={() => {
                setCustModalVisible(false);
              }}
              onSubmit={(value) => {
                value.forEach((item:any) => {
                  item.customerName=item.name;
                  item.customerId=item.id;
                });
                var data=[...value,...currentData]                
                setCustModalVisible(false);
                setCurrentData(data);
              }}
              modalVisible={custModalVisible}
              values={currentData}
              columns={chooseCustomer}
              requestFunction={custData}
          />
          {/* <ModalForm  title="选择区域"
            onVisibleChange={v=>{
              setAreaVisible(v);
            }}
            modalProps={{
              destroyOnClose:true,
              forceRender:true
            }}
            visible={areaVisible}
            onFinish={async (values: any) => {
                if(values.areas){
                  var provincesLabel = currentArea[0].label
                  var cityLabel = currentArea[1].label
                  var value:any = {provinces:values.areas[0],city:values.areas[1],cid:`${values.areas[0]}-${values.areas[1]}`,provincesLabel,cityLabel}
                  for(var i =0;i<areaData.length;i++){
                    if(areaData[i].cid === value.cid){
                      message.warning('已添加该区域，请重新选择！');
                      return false;
                    }
                  }
                  var param={salesId:editModel?.id,areaInfo:[value]}
                  var val = await insertSalesTeamArea(param);
                  if(val.errorCode==='200'){

                    var params:any={};
                    params.salesId=editModel.id;
                    val = await findSalesAreaBySalesId({...params});
                    if(val.errorCode==='200'){
                      val.data.forEach((e:any)=>{
                        e.cid = `${e.provinces}-${e.city}`
                      })
                      setAreaData(val.data);
                    }   
                    return true;
                  }else{
                    message.error(val.errorMessage)
                    return false;
                  }
                }

            }}
          >
          <Form.Item
            name="areas"
            label="省/市"
          >
              <Cascader
                options={areas}
                // value={editModel?.areas}
                placeholder="请选择"
                onChange={onAreaChange}
            />
          </Form.Item>
          </ModalForm> */}
          <ModalForm
            title="销售导入"
            onVisibleChange={v=>{
              setShowImport(v);
            }}
            modalProps={{
              destroyOnClose:true,
              forceRender:true
            }}
            visible={showImport}
            onFinish={async (values: any) => {
              console.log(values);
               return true;
            }}
         >
             <div style={{margin:'10px 0 20px 0'}}><a href="/xwyl/attach/salesHosShip.xlsx" download="销售模板.xlsx"><Button type="primary"> <FileExcelOutlined />销售模板下载</Button></a></div>
            <ProFormUploadDragger label="选择excel上传" name="file" action='/xwyl/salesTeam/salesTeamHospImport' fieldProps={{name:'file',headers:{'authorization':sessionStorage.getItem('token') as string}}}  max={1} onChange={onFileUpload} />

         </ModalForm>

         <Modal
          visible={errorVisible}
          title="导入错误提示"
          width={800}
          footer={null}
          destroyOnClose={true}
          onCancel={handleCancel}
        >
        <Table dataSource={errInfo} style={{height:400}} columns={errorColumn} pagination={false} rowKey="rownum"
        ></Table>
        </Modal>
  </PageContainer>
  );
};
